# -*- coding: utf-8 -*-

'''eof
name:个人风险指数
code:IG07_CreditRickIndex
tableName:
columnName:
groups:个人通用模块
dependencies:EG_CASE_EDMP
type:常用指标
datasourceType:在线指标
description:
eof'''

import io
import sys
import pandas as pd
import json
from datetime import datetime

reload(sys)
sys.setdefaultencoding('utf-8')


def isfloat(x):
    '''
    判断x为float类型
    :param x:
    :return:
    '''
    try:
        if isinstance(float(x), float):
            if str(x) in ['inf', 'infinity', 'INF', 'INFINITY', 'True', 'NAN', 'nan', 'False', '-inf', '-INF',
                          '-INFINITY', '-infinity', 'NaN', 'Nan']:
                return False
            else:
                return True
        else:
            return False
    except:
        return False


def getTable1(object, caseType, tableName):
    """
    object: 'person','enterprise'
    caseType:'civil','administrative','preservation','criminal','bankrupt','implement'
    tableName:'cases','count'
    """
    null_type_list = ['', ' ', None, 'null', 'Null', 'NULL', '/', '-', '--']
    if object == 'enterprise':
        try:
            data1 = EG_CASE_EDMP.get('data').get('FR001')
            if data1 in null_type_list:
                return u'缺失值'
            elif data1 == []:
                pass
            else:
                try:
                    data1 = data1[0].get(caseType)
                    if data1 == {} or data1 == '':
                        pass
                    else:
                        data1 = data1.get(tableName)
                        if data1 in null_type_list:
                            return u'缺失值'
                        else:
                            pass
                except:
                    return u'缺失值'
            data2 = EG_CASE_EDMP.get('data').get('R001')
            if data2 in null_type_list:
                return u'缺失值'
            elif data2 == []:
                pass
            else:
                try:
                    data2 = data2[0].get(caseType)
                    if data2 == {} or data2 == '':
                        pass
                    else:
                        data2 = data2.get(tableName)
                        if data2 in null_type_list:
                            return u'缺失值'
                        else:
                            pass
                except:
                    return u'缺失值'
            data3 = EG_CASE_EDMP.get('data').get('SR001')
            if data3 in null_type_list:
                return u'缺失值'
            elif data3 == []:
                pass
            else:
                try:
                    data3 = data3[0].get(caseType)
                    if data3 == {} or data3 == '':
                        pass
                    else:
                        data3 = data3.get(tableName)
                        if data3 in null_type_list:
                            return u'缺失值'
                        else:
                            pass
                except:
                    return u'缺失值'
        except:
            return u'缺失值'

        if tableName == 'cases':
            if (data1 == [] or data1 == {} or data1 == '') and (data2 == [] or data2 == {} or data2 == '') and (
                    data3 == [] or data3 == {} or data3 == ''):
                return None
            else:
                data = []
                for i in data1:
                    if i not in null_type_list and i != {} and i != '' and i != []:
                        data.append(i)
                    else:
                        pass
                for j in data2:
                    if j not in null_type_list and j != {} and j != '' and j != []:
                        data.append(j)
                    else:
                        pass
                for k in data3:
                    if k not in null_type_list and k != {} and k != '' and k != []:
                        data.append(k)
                    else:
                        pass
        else:
            data = []
            for i in [data1, data2, data3]:
                if i not in null_type_list and i != {} and i != '':
                    data.append(i)
                else:
                    return u'缺失值'
    else:
        try:
            data1 = EG_CASE_EDMP.get('data').get('FR002')
            if data1 in null_type_list:
                return u'缺失值'
            elif data1 == []:
                pass
            else:
                try:
                    data1 = data1[0].get(caseType)
                    if data1 == {} or data1 == '':
                        pass
                    else:
                        data1 = data1.get(tableName)
                        if data1 in null_type_list:
                            return u'缺失值'
                        else:
                            pass
                except:
                    return u'缺失值'
            data2 = EG_CASE_EDMP.get('data').get('R002')
            if data2 in null_type_list:
                return u'缺失值'
            elif data2 == []:
                pass
            else:
                try:
                    data2 = data2[0].get(caseType)
                    if data2 == {} or data2 == '':
                        pass
                    else:
                        data2 = data2.get(tableName)
                        if data2 in null_type_list:
                            return u'缺失值'
                        else:
                            pass
                except:
                    return u'缺失值'
        except:
            return u'缺失值'

        if tableName == 'cases':
            if (data1 == [] or data1 == {} or data1 == '') and (data2 == [] or data2 == {} or data2 == ''):
                return None
            else:
                data = []
                for i in data1:
                    if i not in null_type_list and i != {} and i != '' and i != []:
                        data.append(i)
                    else:
                        pass
                for j in data2:
                    if j not in null_type_list and j != {} and j != '' and j != []:
                        data.append(j)
                    else:
                        pass
        else:
            data = []
            for i in [data1, data2]:
                if i not in null_type_list and i != {} and i != '':
                    data.append(i)
                else:
                    return u'缺失值'

    return data


def getTable2(object, caseType):
    """
    object: 'enterprise'
    caseType:'sxbzxr','xgbzxr'
    """
    null_type_list = ['', ' ', None, 'null', 'Null', 'NULL', '/', '-', '--']
    data = []
    if object == 'person':
        try:
            data1 = EG_CASE_EDMP.get('data').get('FR004')
            if data1 in null_type_list:
                return u'缺失值'
            elif data1 == [] or data1 == '':
                pass
            else:
                for i in data1:
                    try:
                        sxbzxr1 = i.get(caseType)
                        if sxbzxr1 == [] or sxbzxr1 == '':
                            pass
                        elif sxbzxr1 in null_type_list:
                            return u'缺失值'
                        else:
                            for j in sxbzxr1:
                                data.append(j)
                    except:
                        return u'缺失值'

            data2 = EG_CASE_EDMP.get('data').get('R004')
            if data2 in null_type_list:
                return u'缺失值'
            elif data2 == [] or data2 == '':
                pass
            else:
                for i in data2:
                    try:
                        sxbzxr2 = i.get(caseType)
                        if sxbzxr2 == [] or sxbzxr2 == '':
                            pass
                        elif sxbzxr2 in null_type_list:
                            return u'缺失值'
                        else:
                            for j in sxbzxr2:
                                data.append(j)
                    except:
                        return u'缺失值'
        except:
            return u'缺失值'
    else:
        return u'缺失值'

    return data


def int_check(num):
    try:
        int(num)
        return True
    except:
        return False


def float_check(num):
    try:
        float(num)
        return True
    except:
        return False


# 统一转成datetime对象，只能转年月日的字符串
def date_format(str):
    import re
    r = re.compile(r'\D+')
    try:
        time = str[0:10]
        date = datetime.strptime(time, '%Y.%m.%d').strftime('%Y%m%d')
    except:
        try:
            date = datetime.strptime(time, '%Y-%m-%d').strftime('%Y%m%d')
        except:
            try:
                date = datetime.strptime(time, '%Y/%m/%d').strftime('%Y%m%d')
            except:
                try:
                    tmp = r.sub('', time)
                    date = datetime.strptime(tmp, '%Y%m%d').strftime('%Y%m%d')
                except:
                    return None
    return date


def get_shixin_zhixing():
    last_year_list = [(datetime.now() - pd.tseries.offsets.DateOffset(years=i)).strftime('%Y-%m-%d') for i in
                      [5, 3, 2, 0]]
    shixin = getTable2('person', 'sxbzxr')
    zhixing = getTable1('person', 'implement', 'cases')
    null_type_list = ['', ' ', None, 'null', 'Null', 'NULL', '/', '-', '--', u'暂无']
    Factor = []
    if zhixing == u'缺失值':
        return u'缺失值'
    elif zhixing is None:
        pass
    else:
        if len(zhixing) >= 1:
            for i in zhixing:
                if i == {} or i == [] or i == '':
                    pass
                else:
                    casecode = i.get('c_ah')
                    if casecode in null_type_list:
                        return u'缺失值'
                    else:
                        hxah = i.get('c_ah_hx')
                        if hxah not in null_type_list:
                            pass
                        else:
                            ssdw = i.get('n_ssdw')
                            if ssdw in null_type_list:
                                return u'缺失值'
                            elif ssdw == u'申请人' or ssdw == u'申请执行人':
                                pass
                            else:
                                caseTime = i.get('d_jarq')
                                if caseTime in null_type_list:
                                    caseTime = i.get('d_larq')
                                    if caseTime in null_type_list:
                                        return u'缺失值'
                                    else:
                                        pass
                                else:
                                    pass

                                CaseMoney = i.get('n_jabdje')  # 结案标的金额
                                if CaseMoney in null_type_list or isfloat(CaseMoney) is False:
                                    CaseMoney = i.get('n_jabdje_gj')  # 结案标的金额估计
                                    if CaseMoney in null_type_list or isfloat(CaseMoney) is False:
                                        CaseMoney = i.get('n_sqzxbdje')  # 申请执行标的金额
                                        if CaseMoney in null_type_list or isfloat(CaseMoney) is False:
                                            return u'缺失值'

                                if date_format(caseTime) is None:
                                    return u'缺失值'
                                if date_format(last_year_list[2]) < date_format(caseTime) <= date_format(
                                        last_year_list[3]):
                                    if float(CaseMoney) <= 6000:
                                        Factor.append(0)
                                    else:
                                        Factor.append(1)
                                elif date_format(last_year_list[1]) < date_format(caseTime) <= date_format(
                                        last_year_list[2]):
                                    if float(CaseMoney) <= 15000:
                                        Factor.append(0)
                                    else:
                                        Factor.append(1)
                                elif date_format(last_year_list[0]) < date_format(caseTime) <= date_format(
                                        last_year_list[1]):
                                    if float(CaseMoney) <= 25000:
                                        Factor.append(0)
                                    else:
                                        Factor.append(1)
                                else:
                                    Factor.append(0)
        else:
            pass
    zhixing_count = sum(Factor)

    shixin_count = 0
    if shixin == u'缺失值':
        return u'缺失值'
    elif shixin == []:
        pass
    else:
        for i in shixin:
            ah = i.get('ah')
            if ah in null_type_list:
                return u'缺失值'
            else:
                shixin_count += 1

    return shixin_count * 10 + zhixing_count * 5

result = get_shixin_zhixing()